package meijuli.com.join51.business.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import com.jhx.common.model.Event;
import com.jhx.common.model.User;
import com.jhx.common.model.Video;
import com.jhx.common.thirdparty.db.DBHelper;
import com.jhx.common.utils.Constants;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import com.jhx.video.comment.CommentActivity;
import com.jhx.video.draftbox.DraftBoxActivity;
import com.jhx.video.store.StoreActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.AddressActivity;
import meijuli.com.join51.business.activity.ClassificationActivity;
import meijuli.com.join51.business.activity.CollectMoneyActivity;
import meijuli.com.join51.business.activity.CommodityManagementActivity;
import meijuli.com.join51.business.activity.MyFansActivity;
import meijuli.com.join51.business.activity.OrderManagerActivity;
import meijuli.com.join51.business.activity.PhotosManagerActivity;
import meijuli.com.join51.business.activity.QrActivity;
import meijuli.com.join51.business.activity.RechargeActivity;
import meijuli.com.join51.business.activity.SettingActivity;
import meijuli.com.join51.business.activity.WalletActivity;
import meijuli.com.join51.business.adapter.MainItemAdapter;
import meijuli.com.join51.business.adapter.OptionsAdapter;
import com.jhx.common.model.EventBean;
import meijuli.com.join51.business.model.Options;
import meijuli.com.join51.business.model.Status;
import meijuli.com.join51.business.model.UserData;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.serviceprovide.ServiceProvideActivity;
import meijuli.com.join51.business.utils.StringUtil;
import retrofit2.Call;

/**
 * 验证后的页面
 *
 * @author wenqin 2017-04-25 09:51
 */

public class ReviewAfterFragment extends BaseFragment implements OptionsAdapter.OnItemClickListener,
        MainItemAdapter.OnItemClickListener {
    CircleImageView mHeadIcon;
    TextView mAccount;
    TextView mPhone;
    TextView mDateTime;
    RecyclerView mOptionsRv;
    RelativeLayout mAccountStatus;
    RelativeLayout mHeadView;
    TextView mLocationTxt;
    TextView mSettingTxt;
    TextView mDraftCountText;
    TextView mVideoManagerTxt;
    RelativeLayout mDraftBoxRelative;
    TextView mVideosTxt;
    TextView mFansTxt;
    private User mUser;
    private Status mStatus;
    private TextView mCommentTxt;
    private TextView mPhotoTxt;
    private ArrayList<Video> mVideoList;
    private Call<HttpResponse<UserData>> mCall;
    private Call<HttpResponse<Status>> mStatusCall;
    private List<Options> mOptionsList = new ArrayList<>();
    private List<Options> mVerticalOptionsList = new ArrayList<>();
    private OptionsAdapter adapter;
    private MainItemAdapter mainItemAdapter;
    public static String KEY_STATUS = "user_status";

    public static ReviewAfterFragment newInstance(Status status) {
        Bundle args = new Bundle();
        args.putSerializable(KEY_STATUS, status);
        ReviewAfterFragment fragment = new ReviewAfterFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_review_after, container, false);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return v;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mHeadIcon = view.findViewById(R.id.head_icon);
        mAccount = view.findViewById(R.id.account);
        mPhone = view.findViewById(R.id.phone);
        mDateTime = view.findViewById(R.id.date_time);
        mOptionsRv = view.findViewById(R.id.options_rv);
        mPhotoTxt = view.findViewById(R.id.txt_photo_manager);
        mAccountStatus = view.findViewById(R.id.rl_account_info);
        mHeadView = view.findViewById(R.id.rl_head);
        mLocationTxt = view.findViewById(R.id.txt_location);
        mSettingTxt = view.findViewById(R.id.txt_setting);
        mDraftCountText = view.findViewById(R.id.txt_draft_box);
        mVideoManagerTxt = view.findViewById(R.id.txt_video_manager);
        mDraftBoxRelative = view.findViewById(R.id.rl_draft_box);
        mFansTxt = view.findViewById(R.id.txt_fans);
        mVideosTxt = view.findViewById(R.id.txt_videos);
        mCommentTxt = view.findViewById(R.id.txt_comment);
        mHeadIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onHeadIconClick();
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        try {
            mStatus = (Status) getArguments().getSerializable(KEY_STATUS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mUser = UserManager.get().getUser();
         if (mUser == null) {
             return;
         }
         initView();
         initData();
         initListener();
    }
    private void initView() {
        refreshUI();

        mOptionsRv.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        adapter = new OptionsAdapter(getActivity(), mOptionsList);
        mOptionsRv.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        mOptionsRv.setNestedScrollingEnabled(false);

        mainItemAdapter = new MainItemAdapter(getActivity(), mVerticalOptionsList);
        mainItemAdapter.setOnItemClickListener(this);
    }

    private void refreshUI() {
        mPhone.setText(StringUtil.hiePhoneNum(mUser.getPhone()));
        mAccount.setText(StringUtil.limitAccounNameLength(mUser.getBusinessName()));
        mAccountStatus.setVisibility(mUser.getAuthStatus() ==
                Constants.ApprovalStatus.APPROVAL_SUCCESS ? View.GONE: View.VISIBLE);
        if(TextUtils.isEmpty(mStatus.getVideoNum())) {
            mVideosTxt.setText("视频数：0");
        } else {
            mVideosTxt.setText("视频数："+ mStatus.getVideoNum());
        }
        if(TextUtils.isEmpty(mStatus.getCollectionNum())) {
            mFansTxt.setText("粉丝数：0" );
        } else {
            mFansTxt.setText("粉丝数：" + mStatus.getCollectionNum());
        }
        if (TextUtils.isEmpty(mUser.getHeadImage())) {
            requestUserMsg();
        }
        if (!TextUtils.isEmpty(mUser.getHeadImage())) {
            Glide.with(this)
                    .load(mUser.getHeadImage())
                    .error(R.mipmap.icon_header)
                    .into(mHeadIcon);
        }

        mHeadView.setVisibility(View.VISIBLE);
        if (mainItemAdapter != null) {
            mainItemAdapter.notifyDataSetChanged();
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    private void initData() {
        initPotionsList();
        mVideoList = new ArrayList<>();
        getDraftBox();
    }

    private void initPotionsList() {
        mOptionsList.clear();
        mOptionsList.add(new Options(R.mipmap.wallet, "钱包", Options.STATUS_WALLET));
        mOptionsList.add(new Options(R.mipmap.collect_money, "收款", Options.STATUS_COLLECT_MONEY));
        mOptionsList.add(new Options(R.mipmap.order_management, "订单管理", Options.STATUS_ORDER));
    }

    @Subscribe()
    public void onEvent(EventBean eventBean) {
        if (eventBean != null) {
            if (eventBean.getStatus() == EventBean.STATUS_HOME_MSG) {
                mUser = UserManager.get().getUser();
                Glide.with(this).load(mUser.getHeadImage()).error(R.mipmap.icon_header).into(mHeadIcon);
                mAccount.setText(StringUtil.limitAccounNameLength(mUser.getBusinessName()));
            }
        }
    }

    @Subscribe
    public void onEvent(Event event) {
        if(event != null) {
            if(event.getCode() == Video.Companion.getCODE_ADD()) {
                getDraftBox();
            }
            if(event.getCode() == Video.Companion.getCODE_POST_SUCCESS()) {
                getDraftBox();
                getAuthStatus();
            }
        }
    }

    public void initListener() {
        mLocationTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 定位
                AddressActivity.start(getActivity());
            }
        });

        mSettingTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
            }
        });

        mVideoManagerTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), StoreActivity.class);
                startActivity(intent);
            }
        });

        mDraftBoxRelative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), DraftBoxActivity.class);
                startActivity(intent);
            }
        });

        mCommentTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CommentActivity.class);
                startActivity(intent);
            }
        });

        mPhotoTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), PhotosManagerActivity.class);
                startActivity(intent);
            }
        });
    }

    private void getDraftBox() {
        List<Video> videos = DBHelper.Companion.queryAll(Video.class);
        if(videos.size() > 0) {
            mVideoList.clear();
            mVideoList.addAll(videos);
            if(videos.size() <= 99) {
                mDraftCountText.setText("" + videos.size());
            } else {
                mDraftCountText.setText("99+");
            }
            mDraftCountText.setVisibility(View.VISIBLE);
        } else {
            mDraftCountText.setVisibility(View.GONE);
        }
    }

    void onHeadIconClick() {
        Intent intent = new Intent(getActivity(), StoreActivity.class);
        startActivity(intent);
    }

    @Override
    public void itemClick(int position) {
        optionsClick(mOptionsList.get(position).getStatus());
    }

    @Override
    public void onItemClick(int position) {
        optionsClick(mVerticalOptionsList.get(position).getStatus());
    }

    private void optionsClick(int status) {
        Intent intent;
        // 不区分是否会员过期的点击事件
        switch (status) {
            case Options.STATUS_MY_FRIEND:
                // 我的粉丝
                intent = new Intent(getActivity(), MyFansActivity.class);
                startActivity(intent);
                return;
            case Options.STATUS_SERVICE_BUSINESS:
                // 申请品牌服务商
                intent = new Intent(getActivity(), ServiceProvideActivity.class);
                startActivity(intent);
                return;
            case Options.STATUS_QR_CODE:
                // 我的二维码
                intent = new Intent(getActivity(), QrActivity.class);
                startActivity(intent);
                return;
            case Options.STATUS_RECHARGE:
                // 预购
                intent = new Intent(getActivity(), RechargeActivity.class);
                startActivity(intent);
                return;
            case Options.STATUS_COLLECT_MONEY:
                // 付款
                intent = new Intent(getActivity(), CollectMoneyActivity.class);
                startActivity(intent);
                return;
            default:

                break;
        }

        // 区分是否会员过期的点击事件
        switch (status) {
            case Options.STATUS_COMMODITY:
                // 商品
                intent = new Intent(getActivity(), CommodityManagementActivity.class);
                startActivity(intent);
                break;
            case Options.STATUS_CLASSIFICATION:
                // 分类管理
                intent = new Intent(getActivity(), ClassificationActivity.class);
                startActivity(intent);
                break;
            case Options.STATUS_ORDER:
                // 订单管理
                intent = new Intent(getActivity(), OrderManagerActivity.class);
                startActivity(intent);
                break;
            case Options.STATUS_WALLET:
                // 钱包
                intent = new Intent(getActivity(), WalletActivity.class);
                startActivity(intent);
                break;
            default:

                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void getAuthStatus() {
        mStatusCall = ApiManager.get().getApiService(ApiService.class).getAuthStatus();
        HttpRequest.getRequest().autoRecycle(this).start(mStatusCall, new ResponseCallback<Status>() {

            @Override
            public void onSuccess(String url, Status data) {
                if (data == null) {
                    return;
                }
                mStatus = data;
                refreshUI();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);

            }
        });
    }

    /**
     * 请求个人信息数据
     */
    private void requestUserMsg() {
        showLoadingDialog();
        mCall = ApiManager.get().getApiService(ApiService.class).getUserInfo();
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<UserData>() {

            @Override
            public void onSuccess(String url, UserData data) {
                dismissDialog();
                if(data == null) {
                    return;
                }
                mUser = data.getUser();
                if (mUser != null) {
                    UserManager.get().setUser(mUser);
                    Glide.with(ReviewAfterFragment.this)
                            .load(mUser.getHeadImage())
                            .error(R.mipmap.icon_header)
                            .into(mHeadIcon);
                } else {
                    ToastUtil.getInstance().showToast(getActivity(), "更新头像失败");
                }
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }
}
